package org.springframework.boot.autoconfigure.mock.strategy;

import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mock.model.MockResMeta;
import org.springframework.boot.autoconfigure.mock.model.MockResTypeEnum;

/**
 * @author: hooware
 * @Date: 2021/12/26 18:15
 * @Description:
 */
public class JsonValueMockResProcessor implements IMockResProcessor {

    @Autowired
    private Gson gson;

    @Override
    public boolean match(MockResTypeEnum mockResTypeEnum) {
        return MockResTypeEnum.JSON.equals(mockResTypeEnum);
    }

    @Override
    public Object mockProcess(MockResMeta mockResMeta) {
        final String value = mockResMeta.getValue();
        // 1.mockResponse的value设置为json字符串
        if (value.startsWith("{") || value.startsWith("[")) {
            return gson.fromJson(value, mockResMeta.getReturnType());
        }
        // 2.不符合策略条件时默认返回null进行handler兜底
        return null;
    }
}
